import { createApp, type Directive, type DirectiveBinding, type ComponentPublicInstance } from 'vue'
import Loading from '@/components/loading/index.vue'

interface el extends HTMLElement {
  instance?: ComponentPublicInstance
}

// g-relative 是在 base.sass 中定义好的 position: relative
const relativeCls = 'g-relative'
export default {
  mounted(el: el, binding: DirectiveBinding) {
    const app = createApp(Loading)
    el.instance = app.mount(document.createElement('div'))
    if (binding.value) {
      append(el)
    }
  },
  updated(el: el, binding: DirectiveBinding) {
    // 更新的时候，loading 为 true，则还是执行 append(el)，为 false，执行 remove(el)
    if (binding.value !== binding.oldValue) {
      binding.value ? append(el) : remove(el)
    }
  }
} as Directive

function append(el: el) {
  // 获取元素当前样式
  const style = getComputedStyle(el)
  // 如果样式不属于以下三种之一，则给 el 添加需要的定位
  if (!['absolute', 'fixed', 'relative'].includes(style.position)) {
    // 添加样式
    addClass(el, relativeCls)
  }
  el.appendChild(el.instance!.$el)
}
function remove(el: el) {
  removeClass(el, relativeCls)
  el.removeChild(el.instance!.$el)
}

export function addClass(el: el, className: string) {
  if (!el.classList.contains(className)) {
    el.classList.add(className)
  }
}

export function removeClass(el: el, className: string) {
  el.classList.remove(className)
}
